package com.zhengtoudai.http.callback;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.zhengtoudai.ui.activity.LoginActivity;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * 作者：黑哥 on 2016/8/25 11:23
 */
public class SubscriberCallBack<T> extends Subscriber<T> {
    private Context mContext;
    private ApiCallback<T> apiCallback;

    public SubscriberCallBack(Context context,ApiCallback<T> apiCallback) {
        this.apiCallback = apiCallback;
        this.mContext=context;

    }

    @Override
    public void onCompleted() {
        apiCallback.onCompleted();
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            //httpException.response().errorBody().string()
            int code = httpException.code();
            Log.e("LW","返回请求code="+code);
            String msg = httpException.getMessage();
            if (code == 504) {
                msg = "网络不给力";
            }if(code==401){
                mContext.startActivity(new Intent(mContext,LoginActivity.class));
                return;
            }
            apiCallback.onError(e);

            apiCallback.onFailure(code, msg);
        } else {
            apiCallback.onFailure(0, e.getMessage());
        }
        apiCallback.onCompleted();
    }

    @Override
    public void onNext(T t) {
        apiCallback.onSuccess(t);
    }
}
